<script setup lang="ts">
import { Search, Refresh } from "@element-plus/icons-vue";

import {
  addTagApi,
  deleteTagsApi,
  getTagFormApi,
  getTagPageApi,
  updateTagApi,
} from "@/api/tag";
import { TagForm, TagQuery, TagVo } from "@/api/tag/type";

// 查询参数信息
const queryParams = reactive(<TagQuery>{
  pageNum: 1,
  pageSize: 10,
});
// 查询框
const queryFormRef = ref(ElForm);
const dataTableRef = ref();
const total = ref(0);
const tableLoading = ref(false);
const dataList = ref(<TagVo[]>[]);
const removeIds = ref([]); // 删除ID集合 用于批量删除

const tagFormRef = ref(ElForm);

/** 表单内容 */
const formData = reactive(<TagForm>{});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "标签名称不能为空", trigger: "blur" }],
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "add-form",
  width: 500,
  title: "",
});

/** 获取数据 */
const getDataList = async () => {
  tableLoading.value = true;
  await getTagPageApi(queryParams)
    .then(({ data: res }) => {
      dataList.value = res.data.records;
      total.value = res.data.total;
    })
    .finally(() => {
      tableLoading.value = false;
    });
  tableLoading.value = false;
};

/** 查询操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getDataList();
};

/** 重置查询表单字段 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

/** 关闭 Dialog */
const closeDialog = () => {
  tagFormRef.value.resetFields();
  Object.assign(formData, {});
  dialog.visible = false;
};

/** 打开dialog */
const openDialog = (id?: number) => {
  if (id) {
    // 先查询
    getTagFormApi(id).then(({ data: res }) => {
      if (res.code === 200) {
        Object.assign(formData, { ...res.data });
        dialog.visible = true;
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    dialog.visible = true;
  }
};

/** 提交表单 */
const handleSubmit = () => {
  // 如果有类型就要进行类型判断，这里没有
  // 判断表单是否带有ID，如果由就是更新
  tagFormRef.value.validate((valid: any) => {
    if (valid) {
      if (formData.id) {
        updateTagApi(formData).then(({ data: res }) => {
          if (res.code == 200) {
            dialog.visible = false;
            ElMessage.success("更新成功");
            handleQuery();
          } else {
            ElMessage.error(res.msg);
          }
        });
      } else {
        addTagApi(formData).then(({ data: res }) => {
          if (res.code == 200) {
            dialog.visible = false;
            ElMessage.success("添加");
            handleQuery();
          } else {
            ElMessage.error(res.msg);
          }
        });
      }
    }
  });
};

/** 删除 */
const handleDelete = (id?: number) => {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除标签?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteTagsApi(ids).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  });
};

/** 选中项 */
const handleSelectionChange = (selection: any) => {
  removeIds.value = selection.map((item: any) => item.id);
};

onMounted(() => {
  getDataList();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="标签名称" prop="name">
          <el-input
            style="width: 200px"
            v-model="queryParams.name"
            placeholder="请输入文章名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            class="!w-[120px]"
            v-model="queryParams.status"
            clearable
            placeholder="请选择"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" type="primary" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" plain @click="openDialog()">
          <i-ep-plus />新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />删除
        </el-button>
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="tableLoading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标签名称" align="center" prop="name" />
        <el-table-column label="点击次数" align="center" prop="clickCount" />
        <el-table-column label="排序" align="center" prop="sort" />

        <el-table-column label="状态" align="center" prop="categoryId">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit />修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getDataList"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="tagFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="formData.name"
            :readonly="!!formData.id"
            placeholder="请输入标签名称"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
